<!DOCTYPE html>
<html>
<head>
    <title>心理课程新增</title>
    {% include 'admin/common/header.html' %}
    <style>
        .layui-form-item {
            margin-top: 17px !important;
            margin-bottom: 17px !important;
        }

        .layui-table-cell {
            height: 45px;
            line-height: 45px;
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-row layui-col-space10">
    {# 左侧栏 #}
    <div class="layui-col-md3">
        {# 个人信息卡片 #}
        <div class="layui-card">
            <div class="layui-card-header">
                课程信息
            </div>
            <div class="layui-card-body" style="padding: 25px;">
                <div class="layui-form" action="">
                    <div class="layui-form-item">
                        <label class="layui-form-label">课程图标</label>
                        <div class="layui-input-block">
                            <div class="user-info-head" id="userInfoHead">
                                <img id="course_icon" src="/static/admin/admin/images/SF_logo.png" width="115px"
                                     height="115px" alt="">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">课程名称</label>
                        <div class="layui-input-block">
                            <input type="text" id="course_name" lay-verify="required" placeholder="请输入课程名称"
                                   autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">课程类型</label>
                        <div class="layui-input-block">
                            <select id="course_type">
                                <option value="0"></option>
                                <option value="1">诱导积极心理</option>
                                <option value="2">维持平静心理</option>
                                <option value="3">产生消极心理</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item layui-form-text">
                        <label class="layui-form-label">课程描述</label>
                        <div class="layui-input-block">
                            <textarea id="course_description" placeholder="请输入课程详细信息"
                                      class="layui-textarea"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {# 登录信息卡片 #}
        <div class="layui-card">
            <div class="layui-card-header">
                课程详细信息选择
            </div>
            <div class="layui-card-body">
                <div class="layui-form">

                    <div class="layui-form-item">
                        <label class="layui-form-label">性别</label>
                        <div class="layui-input-block">
                            <select id="detail_gender">
                                <option value="0">请选择</option>
                                <option value="1">男性</option>
                                <option value="2">女性</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">犯罪类型</label>
                        <div class="layui-input-block">
                            <select id="detail_crime_type">
                                <option value="0">请选择</option>
                                <option value="1">经济犯</option>
                                <option value="2">财产犯</option>
                                <option value="3">暴力犯</option>
                                <option value="4">其他类型犯罪</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">犯罪年龄</label>
                        <div class="layui-input-block">
                            <select id="detail_age">
                                <option value="0">请选择</option>
                                <option value="1">老年</option>
                                <option value="2">壮年</option>
                                <option value="3">青年</option>
                                <option value="4">少年</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">犯罪倾向</label>
                        <div class="layui-input-block">
                            <select id="detail_tend">
                                <option value="0">请选择</option>
                                <option value="1">惯犯</option>
                                <option value="2">偶犯</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">精神状态</label>
                        <div class="layui-input-block">
                            <select id="detail_mind">
                                <option value="0">请选择</option>
                                <option value="1">常态犯</option>
                                <option value="2">异常犯</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">犯罪情绪</label>
                        <div class="layui-input-block">
                            <select id="detail_emotion">
                                <option value="0">请选择</option>
                                <option value="1">激情犯</option>
                                <option value="2">预谋犯</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {# 右侧栏 #}
    <div class="layui-col-md9">
        {# 个人信息卡片 #}
        <div class="layui-card">
            <div class="layui-card-header">视频与关键点选择</div>
            <div class="layui-card-body">
                <form class="layui-form layui-row layui-col-space12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">视频选择</label>
                        <div class="layui-input-block">
                            <div class="pear-btn pear-btn-primary" id="btn_select_video">点击选择本地视频
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">视频</label>
                        <div class="layui-input-block">
                            <input type="file" id="input_video" accept="video/*" style="display: none;">
                            <video id="video" controls style="width: 600px;"></video>
                        </div>
                    </div>

                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-input-block">
                                <div class="pear-btn pear-btn-primary" id="btn_set_start">设置当前为关键点开始时间
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-input-block">
                                <div class="pear-btn pear-btn-primary" id="btn_set_end">设置当前为关键点结束时间
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-header">视频关键点选择</div>
            <div class="layui-card-body">
                <div class="layui-form layui-row layui-col-space16">
                    <div class="layui-col-md3">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <label class="layui-form-label">开始时间</label>
                            <div class="layui-input-block">
                                <input type="text" class="layui-input" id="keypoint-start"
                                       placeholder="请设置开始时间" disabled>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md1">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <div class="pear-btn pear-btn-primary" id="btn_jump_start">跳转
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <label class="layui-form-label">结束时间</label>
                            <div class="layui-input-block">
                                <input type="text" class="layui-input" id="keypoint-end"
                                       placeholder="请设置结束时间" disabled>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md1">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <div class="pear-btn pear-btn-primary" id="btn_jump_end">跳转
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item" style="margin-bottom: 0;">
                            <label class="layui-form-label">参考情绪</label>
                            <div class="layui-input-inline">
                                <select id="emotion-select" style="max-width: 200px">
                                    <option value="">请选择</option>
                                    <option value="1">积极</option>
                                    <option value="2">平静</option>
                                    <option value="3">消极</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-bottom: 0;text-align: right;margin-right: 20px;">
                        <div class="pear-btn pear-btn-primary" id="btn_add_point">新增关键点
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-bottom: 0;text-align: right;margin-right: 20px;">
                        <table id="user-table" lay-filter="user-table"></table>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-body" style="text-align: right">
                <div id="submit_course" class="layui-btn layui-btn-primary layui-border-green"><i
                        class="layui-icon layui-icon-ok"></i>提交
                </div>
                <div id="cancel_course" class="layui-btn layui-btn-primary layui-border-red"><i
                        class="layui-icon layui-icon-close"></i>取消
                </div>

            </div>
        </div>
    </div>
    >
</div>
</div>
{% include 'admin/common/footer.html' %}


<script type="text/html" id="user-bar">
    <button class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i
            class="pear-icon pear-icon-ashbin"></i>
    </button>
</script>

<script>

    layui.use(['table', 'dropdown', 'dtree', 'form', 'jquery', 'popup', 'common'], function () {
        let $ = layui.jquery
        let layer = layui.layer
        let form = layui.form
        let popup = layui.popup
        let table = layui.table
        let laydate = layui.laydate;
        let dropdown = layui.dropdown;
        let endTime = '10:00:00'
        let MODULE_PATH = '/course/psychology/'
        let file
        let data = []
        // 修改头像
        $('#course_icon').click(function () {
            layer.open({
                type: 2,
                title: '更换图片',
                shade: 0.1,
                area: ['900px', '500px'],
                content: MODULE_PATH + 'cover',
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    window['layui-layer-iframe' + index].submitForm()
                }
            })
        })
        {#
            视频相关事件
        #}

        // 设置选择本地视频
        $('#btn_select_video').click(function () {
            $('#input_video').click()
        })
        $('#input_video').change(function (event) {
            file = event.target.files[0];
            var url = URL.createObjectURL(file);
            $('#video').attr('src', url)
        })

        // 加载完成视频后异步获取视频的时长等信息
        $('#video').on('loadedmetadata', function () {
            // 获取视频时长
            var videoDuration = $('video').prop('duration')
            // 本地视频选择后设置关键点选择相关选项为可用
            $('#keypoint-start').prop('disabled', false)
            $('#keypoint-end').prop('disabled', false)
            $('#emotion-select').prop('disabled', false)
            // 设置可选择时间范围
            endTime = secondToHours(videoDuration)
            laydate.render({
                elem: '#keypoint-start',
                type: 'time',
                // 设置最小时间为0，最大时间为视频时间长度
                min: '00:00:00',
                format: 'HH:mm:ss',
                max: endTime,
                btns: ['clear', 'confirm']
            });
            laydate.render({
                elem: '#keypoint-end',
                type: 'time',
                format: 'HH:mm:ss',
                min: '00:00:00',
                max: endTime,
                btns: ['clear', 'confirm']
            });
        })

        // 视频暂停时，如果开始时间和结束时间为空，会更新开始时间和结束时间
        $('#video').on('pause', function () {
            var currentTime = $('#video').prop('currentTime')
            if ($('#keypoint-start').prop('value') === '') {
                $('#keypoint-start').prop('value', secondToHours(currentTime))
            }
            if ($('#keypoint-end').prop('value') === '') {
                $('#keypoint-end').prop('value', secondToHours(currentTime))
            }
        })
        // 点击设置当前为关键点开始时间按钮的时间处理
        $('#btn_set_start').click(function () {
            if ($('#video').attr('src') === undefined) {
                popup.failure('请选择视频')
                return
            }
            // 设置视频当前时间为视频关键点开始时间
            var currentTime = $('#video').prop('currentTime')
            $('#keypoint-start').val(secondToHours(currentTime))
        })
        // 点击设置当前为关键点结束时间按钮的时间处理
        $('#btn_set_end').click(function () {
            if ($('#video').attr('src') === undefined) {
                popup.failure('请选择视频')
                return
            }
            var currentTime = $('#video').prop('currentTime')
            $('#keypoint-end').val(secondToHours(currentTime))
        })

        {#把秒转化为HH:mm:ss格式#}

        function secondToHours(seconds) {
            var date = new Date(null);
            date.setSeconds(seconds);
            var timeString = date.toISOString().substr(11, 8);
            return timeString;
        }

        {#把HH:mm:ss转化为秒#}

        function hoursToSeconds(timeString) {
            var timeParts = timeString.split(':');
            var hours = parseInt(timeParts[0]);
            var minutes = parseInt(timeParts[1]);
            var seconds = parseInt(timeParts[2]);
            var totalSeconds = hours * 3600 + minutes * 60 + seconds;
            return totalSeconds;
        }


        {#
            实现关键点选择
        #}
        //开始时间改变时联动结束时间改变
        // 视频开始时间跳转
        $('#btn_jump_start').click(function () {
            if ($('#keypoint-start').val() === '') {
                popup.failure('请输入开始时间');
            } else {
                $('#video').prop('currentTime', hoursToSeconds($('#keypoint-start').val()))
            }
        })

        // 视频结束时间跳转
        $('#btn_jump_end').click(function () {
            if ($('#keypoint-start').val() === '') {
                popup.failure('请输入结束时间');
            } else {
                $('#video').prop('currentTime', hoursToSeconds($('#keypoint-end').val()))
            }
        })
        {#
            点击新增关键点后的处理方法
        #}
        $('#btn_add_point').click(function () {
            // 判断是否为空
            if ($('#keypoint-start').val() === '') {
                popup.failure('请输入开始时间');
            } else if ($('#keypoint-end').val() === '') {
                popup.failure('请输入结束时间');
            } else if ($('#emotion-select').val() === '') {
                popup.failure('请输入参考情绪');
            } else {
                var emotion = ''
                switch ($('#emotion-select').val()) {
                    case '1':
                        emotion = "积极";
                        break;
                    case '2':
                        emotion = "平静";
                        break;
                    case '3':
                        emotion = "消极";
                        break;
                }
                // 所有关键点数据都存在data中，在data中插入新数据
                data.push({
                    id: data.length,
                    start: $('#keypoint-start').val(),
                    end: $('#keypoint-end').val(),
                    emotion: emotion
                })
                // 向data中插入新数据后，更新表格
                table.reload('user-table', {
                    data: data
                });
            }
        })

        // 表格数据
        let cols = [
            [
                {
                    title: '关键点开始时间', field: 'keypoint_start', align: 'center', templet: function (d) {
                        return '<input type="text" id= "ID_point_start_' + d.id + '" class="layui-input layui-keypoint-start" value="' + d.start + '"placeholder="请输入开始时间"/>'
                    }
                },
                {
                    title: '关键点结束时间', field: 'kepoint_end', align: 'center', templet: function (d) {
                        return '<input type="text" id= "ID_point_end_' + d.id + '" class="layui-input layui-keypoint-end" value="' + d.end + '"placeholder="请输入结束时间"/>'
                    }
                },
                {
                    title: '参考情绪', field: 'emotion', align: 'center', templet: function (d) {
                        return '<button class="layui-btn layui-btn-primary dropdown-emotion">\n' +
                            '<span>' + d.emotion + '</span>\n' +
                            '<i class="layui-icon layui-icon-down"></i>\n' +
                            '</button>'
                    }
                },
                {title: '操作', toolbar: '#user-bar', align: 'center', width: 130}
            ]
        ]

        // 获取心理的选项
        let dataEmotion = [];
        $('#emotion-select option').each(function () {
            var titleEmotion = $(this).text();
            var idEmotion = $(this).val();
            dataEmotion.push({
                title: titleEmotion,
                id: idEmotion
            });
        });

        // 渲染表格数据
        table.render({
            elem: '#user-table',
            cols: cols,
            skin: 'line',
            data: data,
            page: true,
            limit: 10,
            // 表格加载完成后操作
            done: function (res, curr, count) {
                var options = this;

                // 根据点击的按钮获取按钮所在行的数据
                table.getRowData = function (elem) {
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[options.id][index] || {};
                };
                // 渲染表格每行的开始时间输入框
                $('.layui-keypoint-start').each(function () {
                    laydate.render({
                        // TODO
                        elem: this,
                        type: 'time',
                        min: '00:00:00',
                        max: endTime,
                        btns: ['clear', 'confirm'],
                        // 如果开始时间输入框内的数据发生变化执行以下操作
                        done: function (value, date, endDate) {
                            // 获取操作所在行的数据
                            var rowData = table.getRowData(this.elem);
                            // 找到data中对应的数据进行更新
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].id === rowData.id) {
                                    data[i].start = value
                                }
                            }
                        }
                    });
                })

                // 渲染表格每行的开始时间输入框
                $('.layui-keypoint-end').each(function () {
                    laydate.render({
                        elem: this,
                        type: 'time',
                        min: '00:00:00',
                        max: endTime,
                        btns: ['clear', 'confirm'],
                        done: function (value, date, endDate) {
                            var rowData = table.getRowData(this.elem);
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].id === rowData.id) {
                                    data[i].end = value
                                }
                            }
                        }
                    });
                })

                // 渲染参考情绪的选项框
                $('.dropdown-emotion').each(function () {
                    dropdown.render({
                        elem: this,
                        // trigger: 'hover',
                        // 此处的 data 值，可根据 done 返回的 res 遍历来赋值
                        data: dataEmotion,
                        click: function (obj) {
                            var rowData = table.getRowData(this.elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                            this.elem.find('span').html(obj.title);
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].id === rowData.id) {
                                    data[i].emotion = obj.title
                                }
                            }
                        }
                    });
                })
            }
        })

        // 提交数据
        $('#submit_course').click(function () {
            var course_icon = $('#course_icon').attr('src')
            var course_name = $('#course_name').val()
            if (course_name == '') {
                popup.failure('请输入课程名称')
                return
            }
            var course_type = $('#course_type option:selected').text()
            if ($('#course_type').val() == "0" || $('#course_type').val() == 0) {
                popup.failure('请选择课程类型')
                return
            }
            var course_description = $('#course_description').val()
            var detail_gender = $('#detail_gender option:selected').text()
            if ($('#detail_gender').val() == "0" || $('#detail_gender').val() == 0) {
                popup.failure('未选择犯罪性别')
                return
            }
            var detail_crime_type = $('#detail_crime_type option:selected').text()
            if ($('#detail_crime_type').val() == "0" || $('#detail_crime_type').val() == 0) {
                popup.failure('未选择犯罪类型')
                return;
            }
            var detail_age = $('#detail_age option:selected').text()
            if ($('#detail_age').val() == "0" || $('#detail_age').val() == 0) {
                popup.failure('未选择犯罪年龄')
                return
            }
            var detail_tend = $('#detail_tend option:selected').text()
            if ($('#detail_tend').val() == "0" || $('#detail_tend').val() == 0) {
                popup.failure('未选择倾向')
                return;
            }
            var detail_mind = $('#detail_mind option:selected').text()
            if ($('#detail_mind').val() == "0" || $('#detail_mind').val() == 0) {
                popup.failure('未选择犯罪精神状态')
                return;
            }
            var detail_emotion = $('#detail_emotion option:selected').text()
            if ($('#detail_emotion').val() == "0" || $('#detail_emotion').val() == 0) {
                popup.failure('未选择犯罪情绪')
                return;
            }
            if (!file) {
                popup.failure('请选择视频')
                return
            }
            // 设置视频跨域
            $('#video').crossOrigin = 'anonymous'
            // 获取文件名称
            var filePath = file.name
            // 获取文件后缀(文件类型)
            var index = filePath.lastIndexOf(".");
            var ext = filePath.substring(index);
            // 用当前时间重命名文件,防止文件名称冲突
            let timeStamp = Date.parse(new Date())
            let fileName = timeStamp + ext
            // 设置文件信息
            let formData = new FormData()
            formData.append('file', file, fileName)
            formData.append('fileName', fileName)
            formData.append('fileToken', timeStamp)

            // 弹出等待窗口
            var index = layer.load(0, {
                shade: [0.1, '#fff'] //0.1透明度的白色背景
            });

            // 先上传视频,上传成功的话,上传课程信息,上传课程信息成功后,上传关键帧信息
            $.ajax({
                method: 'post',
                url: '/admin/file/course_men/videos/upload', //用于文件上传的服务器端请求地址
                data: formData,
                processData: false,
                contentType: false,
                success: function (result) {
                    // TODO
                    if (result.success) {
                        var courseInfo = {
                            course_name: course_name,
                            course_icon: $('#course_icon').attr('src'),
                            course_type: course_type,
                            course_description: course_description,
                            detail_gender: detail_gender,
                            detail_crime_type: detail_crime_type,
                            detail_age: detail_age,
                            detail_tend: detail_tend,
                            detail_mind: detail_mind,
                            detail_emotion: detail_emotion,
                            video_path: result.data.src
                        }
                        $.ajax({
                            method: 'post',
                            url: MODULE_PATH + 'add',
                            data: JSON.stringify(courseInfo),
                            contentType: 'application/json',
                            success: function (result) {
                                if (result.success) {
                                    var course_id = result.data.course_id
                                    $.ajax({
                                        method: 'post',
                                        url: MODULE_PATH + 'keypoint',
                                        data: JSON.stringify({
                                            course_id: course_id,
                                            key_points: data
                                        }),
                                        contentType: 'application/json',
                                        success: function (result) {
                                            layer.close(index)
                                            parent.layui.table.reload('user-table')
                                            if (result.success) {
                                                popup.success("新增课程成功")
                                            } else {
                                                popup.failure(result.msg)
                                            }
                                            setTimeout(function () {
                                                parent.layer.close(parent.layer.getFrameIndex(window.name))
                                            }, 1000)
                                        }
                                    })
                                } else {
                                    layer.close(index)
                                    popup.failure(result.msg)
                                }
                            }
                        })
                    }
                }
            })

        })

        $('#cancel_course').click(function () {
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        })


        //
        $('.user-group').click(function () {
            let group = $(this).attr('user-group')
            let field = form.val('user-query-form')
            if (group === '-1') {
                field.deptId = group
                $(this).removeClass('button-default')
                $(this).prev().removeClass('button-primary')
                $(this).prev().addClass('button-default')
                $(this).addClass('button-primary')
            } else {
                field.deptId = group
                $(this).removeClass('button-default')
                $(this).next().removeClass('button-primary')
                $(this).next().addClass('button-default')
                $(this).addClass('button-primary')
            }
            window.refresh(field)
        })

        table.on('tool(user-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj)
            } else if (obj.event === 'edit') {
                window.edit(obj)
            }
        })

        table.on('toolbar(user-table)', function (obj) {
            if (obj.event === 'add') {
                window.add()
            } else if (obj.event === 'refresh') {
                window.refresh()
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj)
            } else if (obj.event === 'collasped') {
                $('.user-left').toggleClass('user-collasped')
                $('.user-main').toggleClass('user-collasped')
                table.resize()
            }
        })

        window.remove = function (obj) {
            layer.confirm('确定要删除该关键点', {icon: 3, title: '提示'}, function (index) {
                layer.close(index)
                // 删除时，除了删除表格中的数据，也要删除data中的数据
                for (var i = 0; i < data.length; i++) {
                    if (data[i].id === obj.data.id) {
                        data.splice(i, 1)
                        break
                    }
                }
                popup.success("删除成功", function () {
                    obj.del()

                })
            })
        }

    })
</script>
</body>
</html>
